<?php

class Admin_Form_User extends Zend_Form
{

	public function init()
	{
		$this->setAction($_SERVER['REQUEST_URI']);
		$this->addElement('Text', 'name', array(
			'label' => 'user.name',
			'required' => true,
		));
		$this->addElement('Text', 'email', array(
			'label' => 'user.email',
			'required' => true,
			'validators' => array('EmailAddress'),
		));
		$this->addElement('Text', 'username', array(
			'label' => 'user.username',
			'validators' => array('Alnum'),
			'required' => true,
		));
		$this->addElement('Password', 'userpass', array(
			'label' => 'user.userpass',
			'validators' => array('Alnum'),
		));
		$this->addElement('Select', 'role', array(
			'label' => 'user.role',
			'multiOptions' => array(
				'member' => 'role.member',
				'editor' => 'role.editor',
				'admin' => 'role.admin',
			),
			'required' => true,
		));
		$this->addElement('Checkbox', 'is_active', array(
			'label' => 'user.active',
		));
		$this->addElement('Submit', 'save', array(
			'label' => 'button.save',
		));
	}

	public function load(Zend_Db_Table_Row $row)
	{
		$data = $row->toArray();
		$this->setDefaults($data);
		$this->userpass->setRequired(is_null($row->user_id));
		if ($this->username)
		{
			$this->username->addValidator(new Zend_Validate_Db_NoRecordExists(array(
				'adapter' => Zend_Db_Table::getDefaultAdapter(),
				'table' => 'user',
				'field' => 'username',
				'exclude' => implode(' AND ', array(
					'user_id != '.(int)$row->user_id,
					'is_deleted = 0',
				))
			)));
		}
	}

	public function save(Zend_Db_Table_Row $row)
	{
		$data = $this->getValues();
		$row->setFromArray($data);
		return $row->save();
	}

}